package leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main4 {


    /**
     * 将扁平化的省市区数据转换成树形结构，方便前端做多级联动
     */
    public static void main(String[] args) {
        String[][] areaArray = new String[][]{
                {"江苏", "南京", "玄武区"},
                {"江苏", "南京", "秦淮区"},

                {"安徽", "安庆", "潜山"},
                {"安徽", "安庆", "大观区"},
                {"安徽", "安庆", "桐城市"},
                {"安徽", "合肥市", "蜀山区"},
                {"安徽", "合肥市", "瑶海区"},

                {"浙江", "杭州市", "上城区"},
                {"浙江", "杭州市", "拱墅区"},
                {"浙江", "杭州市", "萧山区"},
                {"浙江", "宁波市", "江北区"},
        };

        List<Area> list = treeify(areaArray);
        System.out.println(list);

    }

    static List<Area> treeify(String[][] array) {
        // TODO 请在此处添加转换代码
        Map<String, List<String>> pMap = new HashMap<>();
        Map<String, List<String>> cMap = new HashMap();


        List<Area> ans = new ArrayList();
        for (int i = 0; i < array.length; i++) {
            String[] cur = array[i];
            String p = cur[0];
            String c = cur[1];
            String a = cur[2];

            List<String> cList = pMap.getOrDefault(p, new ArrayList());
            cList.add(c);
            pMap.put(p, cList);

            List<String> aList = cMap.getOrDefault(c, new ArrayList());
            aList.add(a);
            cMap.put(c, aList);
        }

        System.out.println(pMap);
        System.out.println(cMap);


        for (Map.Entry<String, List<String>> map : pMap.entrySet()) {

            Area p = new Area(map.getKey());
            List<String> citys = map.getValue();
            List<Area> cityList = new ArrayList<>();
            for (String city : citys) {
                Area cityA = new Area(city);
                List<String> aList = cMap.get(city);
                List<Area> aList1 = new ArrayList<>();
                for (String a : aList) {
                    aList1.add(new Area(a));
                }

                cityA.children = aList1;
                cityList.add(cityA);


            }
            p.children = cityList;

            ans.add(p);
        }

        return ans;

    }


    public static class Area {

        private final String field;
        private List<Area> children;

        public Area(String field) {
            this(field, new ArrayList<>());
        }

        public Area(String field, List<Area> children) {
            this.field = field;
            this.children = children;
        }


        public String getField() {
            return field;
        }

        public List<Area> getChildren() {
            return children;
        }


        @Override
        public String toString() {

            return "{" +
                    "\"field\":\"" + field + '"' +
                    ", \"children\": " + children +
                    '}';
        }
    }
}
